import { Button, Card, Input, Space, Table, Tree, Spin, Upload, Dropdown, Popconfirm } from 'antd';
import { useState, useEffect, useRef } from 'react'
import dynamicColumnJzzyApi from '../../../../../utils/apis/dynamicColumanJzzyApi';
import Api from '../../../../../utils/api';
import JzzyApi from '../../../../../utils/apis/JzzyApi';
import _ from 'lodash'
import { UpCircleOutlined } from '@ant-design/icons';
import ScrollTable from '../../../../common/ScrollTable';
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import { Histogram } from '@antv/g2plot';
import PubSub from 'pubsub-js';
import FetchHelper from '../../../../../utils/helper/fetch-helper';
import { set } from 'ol/transform';
export default function Jzzy(props) {
    const [category, setCategory] = useState();
    const [category2, setCategory2] = useState();
    const [jzzyData, setJzzyData] = useState();
    // const [tableCols,setTableCols]=useState([])
    const [total, setTotal] = useState();
    const [allColumns, setAllColumns] = useState();
    const [loading, setLoading] = useState();
    const rootRef = useRef();


    const [params, setParams] = useState({
        pagesize: 10,
        pageNum: 1,
        jzzyMiddle: '政府综合减灾资源'
    });

    useEffect(() => {
        Api.getJzzyCategroy().then(datas => {
            setCategory(datas)
        })
    }, [])
    useEffect(() => {
        Api.getJzzyCategroy2().then(datas => {
            setCategory2(datas)
        })
    }, [])

    useEffect(() => {
        dynamicColumnJzzyApi.jzzy().then(data => {
            setAllColumns(data);
        })
    }, [])
    const [node,setNode]=useState(null);
    const [jzzyzl,setJzzyzl]=useState(null);
    // console.log('node',node)

    const [value,setValue]=useState();

   //数据展示
    useEffect(() => {
        setLoading(true);
        let promise;
        if(jzzyzl){
            promise =  JzzyApi.list_serch()
        }else{
            promise =  JzzyApi.list_serch(node?.key)
        }
        promise.then(resp => {
            if(value){
                const filterData=resp?.rows.filter(item=>item?.jzzymc.includes(value))
                setJzzyData(filterData)
            }else{
                setJzzyData(resp.rows)
            }
            
            setTotal(resp.total);
        }).finally(e => {
            setLoading(false)
        })
        setJzzyzl(null)
    }, [node,jzzyzl,value])
    // console.log('jzzyData',jzzyData)
    //数据excel表下载地址
    const url = '/admin-api/ybyj/jzzy/export';

    //新增
    const items = category2

    const tableCols = allColumns?.[params.jzzySmall || params.jzzyMiddle] || [];
    const message = '';

    props = {
        name: 'file',
        action: '/admin-api/ybyj/jzzy/import',
        headers: {
            authorization: 'authorization-text',
        },
    }
    //编辑 设置按键跳转路径
    const history = useHistory();
    const jzzyHandleEdit = (record) => {
        history.push(`/manager/jzzyEdit/${record.id}`)
    }
    //查看
    const jzzyHandleLook = (record) => {
        history.push(`/manager/jzzyLook/${record.id}`)
    }
    //新增
    const [keyPath, setKeyPath] = useState();
    const jzzyAddDatas = (keyPath) => {
        history.push(`/manager/jzzyAdd/${keyPath}`)
    }
    const [selectedKey, setSelectedKey] = useState('政府综合减灾资源');
    const handleJudge = (selectedKey, keyPath) => {
        
        if (selectedKey?.children?.length > 1 || selectedKey === '政府综合减灾资源') {
            window.alert('请选择小类')
        }
        else {
            // setKeyPath(node?.key)
            const keyPath = selectedKey?.key
            jzzyAddDatas(keyPath)
        }
    }
    console.log('params.jzzySmall',params.jzzySmall)
    console.log(' params.jzzyMiddle', params.jzzyMiddle)
    //删除按键
    const deleteHandle = (record) => {
        const newjzzyData = jzzyData.filter(function (arr) {
            return arr.id !== record.id
        })
        FetchHelper.deleteJson(`/admin-api/ybyj/jzzy/` + record.id).then(() => alert('删除成功')).catch(error => alert("删除失败") + error)
        setJzzyData(newjzzyData)
    }
    //搜索
    const onSearch = (value) => {
        setValue(value)
        setParams(params => {
            return {
                ...params,
                dwmc: value,
                pageNum: 1
            }
        });
    }
    return <div className='layout-h h100'>
        <Card size='small' className='h100' style={{
            width: 240,
            marginRight: 12,
            overflow: "auto"
        }} title={"调查对象分类"}>
            {category && <Tree className='categray-tree' selectedKeys={[params.jzzySmall || params.jzzyMiddle]}
                treeData={category} blockNode
                defaultExpandAll
                rootStyle={{color:'#aaa'}}
                onSelect={(selectedKeys, { node }) => {
                 setNode(node)
                 setSelectedKey(node)
                 if(node?.children){
                    setJzzyzl(selectedKeys?.[0])
                 }
                    const p = {}
                    if (node.children) {
                        p.jzzyMiddle = selectedKeys?.[0]
                    } else {
                        p.jzzySmall = selectedKeys?.[0]
                    }
                    setParams(params => {
                        return {
                            pageSize: params.pagesize,
                            pageNum: 1,
                            ...p
                        }
                    })
                    

                }}
                fieldNames={{
                    title: 'title',
                    key: 'title'
                }}

            />}
        </Card>
        <Card size='small' className='h100 fill w0' style={{
            position: "relative"
        }} bodyStyle={{
            display: 'flex',
            flexDirection: "column",
            height: "100%"
        }}>
            <div style={{
                marginBottom: 12,
                display: 'flex',
                alignItems: "center",
                justifyContent: "space-between"
            }}>
                <Space>
                    <>
                        <Button onClick={() => handleJudge(selectedKey, keyPath)}>新增</Button>
                        <Upload {...props}>
                            <Button icon={<UpCircleOutlined />}>数据导入</Button>
                        </Upload>
                            {/* <Button type="primary" key="download" onClick={()=>{
                                 fetch(`/admin-api/ybyj/jzzy/exportLike?columnNames=${node?.tag}&key=${node.key}`, {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json;charset=UTF-8'
                                    }
                                }).then(response => response.blob()).then(blob => {
                                    const a = document.createElement("a");
                                    a.download = "data.xls";
                                    a.href = URL.createObjectURL(blob);
                                    a.click();
                                }).catch(error => console.log(error))
                            }}>数据导出</Button> */}
                    </>
                </Space>
                <div>
                    <Input.Search placeholder='输入名称查找'
                        allowClear
                        enterButton="查询"
                        onSearch={onSearch}
                    />
                </div>
            </div>
            {/* {loading && <div style={{
                position:'absolute',
                left:0,
                bottom:0,
                right:0,
                top:0,
                display:'flex',
                alignItems:"center",
                justifyContent:"center"
            }}>
                <Spin />
            </div>} */}
            <div ref={rootRef} className="fill h0">
                {<ScrollTable style={{
                    // border:"1px solid #ddd"
                }}
                    loading={loading}
                    parentNode={rootRef.current}
                    size='small'
                    bordered
                    dataSource={jzzyData}
                    scroll={{
                        x: 320 + _.sumBy(tableCols, 'width'),
                    }}
                    columns={[
                        {
                            title: '单位名称',
                            dataIndex: 'dwmc',
                            fixed: 'left',
                            width: 160

                        }, {
                            title: '减灾资源名称',
                            dataIndex: 'jzzymc',
                            fixed: 'left',
                            width: 160
                        },
                        ...tableCols,
                        {
                            title: '操作',
                            key: 'caozuo',
                            width: 260,
                            render: (text, record) => {
                                return <Space size="middle">
                                    <Button onClick={e => { jzzyHandleLook(record) }}>查看</Button>
                                    <Button onClick={e => { jzzyHandleEdit(record) }}>编辑</Button>
                                    <Popconfirm title="确定删除吗?" onConfirm={e => deleteHandle(record)}>
                                        {/* <Button onComfir={e => { deleteHandle(record) }}>删除</Button> */}
                                        <Button>删除</Button>
                                    </Popconfirm>

                                </Space>

                            }
                        },
                    ].map(item => {
                        return {
                            ...item,
                        }
                    })}
                    pagination={{
                        current: params.pageNum,
                        pageSize: params.pagesize,
                        total,
                    }}
                    onChange={({ current }) => {
                        setParams(params => {
                            return {
                                ...params,
                                pageNum: current
                            }
                        })
                    }}
                />}
            </div>
        </Card>
    </div>;
}